package icu.groot.alan.hotel.controller.account;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import icu.groot.alan.hotel.entity.dao.AccountDo;
import icu.groot.alan.hotel.entity.dto.LoginUserDto;
import icu.groot.alan.hotel.entity.req.AccountLoginRo;
import icu.groot.alan.hotel.entity.req.AccountRegisterRo;
import icu.groot.alan.hotel.entity.req.AccountUpdatePasswordRo;
import icu.groot.alan.hotel.entity.vo.LoginUserVo;
import icu.groot.alan.hotel.service.AccountService;
import icu.groot.alan.hotel.util.BizException;
import icu.groot.alan.hotel.util.GrootApi;
import icu.groot.alan.hotel.util.LoginTokenEntity;
import icu.groot.alan.hotel.util.ResultCodeEnum;
import icu.groot.alan.hotel.util.response.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;


/**
 * User Management
 */
@RestController
@RequestMapping("/acc")
public class AccountController {
    @Resource
    AccountService accountService;

    @ApiOperation("Account Oneself")
    @PostMapping("/oneself")
    public Result<LoginUserVo> oneself(HttpServletRequest request){
        LoginTokenEntity loginTokenEntity = new Gson().fromJson(request.getAttribute(GrootApi.Jwt.HEADER).toString(), LoginTokenEntity.class);
        LoginUserVo loginUserVo = new LoginUserVo();
        GrootApi.BeanCopy.copyProperties(accountService.getById(loginTokenEntity.getAccCode()), loginUserVo);
        return Result.success(loginUserVo);
    }

    @ApiOperation("Account Login")
    @PostMapping("/login")
    public Result<LoginUserVo> login(@RequestBody AccountLoginRo loginRo, HttpServletResponse response){
        LoginUserDto loginUserDto = accountService.login(loginRo);
        response.setHeader(GrootApi.Jwt.HEADER, loginUserDto.getToken());
        LoginUserVo loginUserVo = new LoginUserVo();
        GrootApi.BeanCopy.copyProperties(loginUserDto, loginUserVo);
        return Result.success(loginUserVo);
    }

    @ApiOperation("Account Register")
    @PostMapping("/register")
    public Result<String> register(@RequestBody AccountRegisterRo registerRo){
        AccountDo accountDo = new AccountDo();
        if (accountDo.getAccName() == null || accountDo.getAccName().trim().equals("")){
            accountDo.setAccName(registerRo.getAccPhone());
        }
        BeanUtils.copyProperties(registerRo, accountDo);
        accountDo.setAccBalance(BigDecimal.valueOf(0));
        if (accountService.save(accountDo)){
            return Result.success("注册成功");
        }
        throw new BizException(ResultCodeEnum.SYSTEM_EXCEPTION);
    }

    @ApiOperation("Account Update Password")
    @PostMapping("/update/password")
    public Result<String> updatePassword(@RequestBody AccountUpdatePasswordRo updatePasswordRo, HttpServletRequest request){
        if (updatePasswordRo.getAccPassword() == null || updatePasswordRo.getAccPassword().trim().equals("")){
            throw new BizException(ResultCodeEnum.FAILED.setMessage("新密码不能为空"));
        }
        LoginTokenEntity loginTokenEntity = new Gson().fromJson(request.getAttribute(GrootApi.Jwt.HEADER).toString(), LoginTokenEntity.class);
        AccountDo account = accountService.getById(loginTokenEntity.getAccCode());
        if (account == null){
            throw new BizException(ResultCodeEnum.FAILED.setMessage("用户不存在"));
        }
        if (!account.getAccPassword().equals(updatePasswordRo.getAccPassword())){
            throw new BizException(ResultCodeEnum.FAILED.setMessage("原始密码错误"));
        }
        account.setAccPassword(updatePasswordRo.getAccAgainNewPassword());
        if (!accountService.updateById(account)){
            throw new BizException(ResultCodeEnum.SYSTEM_EXCEPTION);
        }
        return Result.success("修改密码成功");
    }

    @ApiOperation("Account top up")
    @PostMapping("/topup/{amountStr}")
    public Result<LoginUserVo> topUp(@PathVariable("amountStr") String amountStr, HttpServletRequest request){
        LoginTokenEntity loginTokenEntity = new Gson().fromJson(request.getAttribute(GrootApi.Jwt.HEADER).toString(), LoginTokenEntity.class);
        UpdateWrapper<AccountDo> accountDoUpdateWrapper = new UpdateWrapper<>();
        AccountDo byId = accountService.getById(loginTokenEntity.getAccCode());
        BigDecimal amount;
        try {
            amount = new BigDecimal(amountStr);
        }catch (Exception e){
            e.printStackTrace();
            throw new BizException(ResultCodeEnum.FAILED.setMessage("瞎搞?"));
        }
        BigDecimal maxBalance = BigDecimal.valueOf(99999999.99);
        // BigDecimal比较大小，-1小于，0等于，1大于，>-1大于等于，<1小于等于
        if (byId.getAccBalance().add(amount).compareTo(maxBalance) > -1){
            throw new BizException(ResultCodeEnum.FAILED.setMessage("啥意思,搁这套娃呢,想一次性暴富？上限 99999999.99。滚蛋!!!"));
        }
        byId.setAccBalance(byId.getAccBalance().add(amount));
        if (!accountService.updateById(byId)){
            throw new BizException(ResultCodeEnum.SYSTEM_EXCEPTION.setMessage("充值失败"));
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        GrootApi.BeanCopy.copyProperties(byId, loginUserVo);
        return Result.success("充值成功", loginUserVo);

    }
}
